package org.terramagnet.mvcframework.http.signature.impl;

import org.terramagnet.mvcframework.http.Connection;
import org.terramagnet.mvcframework.http.signature.SignException;
import org.terramagnet.mvcframework.http.signature.Signer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author lip
 */
public class InstanceCachedSignature extends AbstractSecretSigner {

    private final Map<String, Signer> cache = new HashMap<String, Signer>();
    private final Class<? extends Signer> prototype;

    public InstanceCachedSignature(Class<? extends Signer> prototype) {
        this.prototype = prototype;
    }

    @Override
    public String sign(Collection<Connection.KeyVal> parameters) throws SignException {
        throw new IllegalStateException("The secret is not set!");
    }

    @Override
    public Signer secret(String secret) {
        try {
            Signer signer = cache.get(secret);
            if (signer == null) {
                synchronized (cache) {
                    Signer s = prototype.newInstance();
                    s.secret(secret);
                    cache.put(secret, s);
                }
            }
            return cache.get(secret);
        } catch (Exception ex) {
            throw new RuntimeException("cannot instance signer", ex);
        }
    }

}
